import ClipboardJS from "clipboard";
import { useCallback, useEffect, useRef, useState } from "react";
import { Button, Input, Form, message, Modal, Flex } from "antd";
import { CopyOutlined, Html5Outlined, OrderedListOutlined } from "@ant-design/icons";

type Props = {
	name: string;
	label?: string;
};
export default function (props: Props) {
	const [setForm] = Form.useForm();
	const form = Form.useFormInstance();
	const clipboardRef = useRef<ClipboardJS>(null);
	const copyBtnRef = useRef<HTMLButtonElement>(null);

	const [open, setOpen] = useState(false);
	const handleOpen = useCallback(() => setOpen(true), []);
	const handleCancel = useCallback(() => setOpen(false), []);

	const multiple = Form.useWatch([props.name, "multiple"]);
	const selector = Form.useWatch([props.name, "selector"]);

	const handleChangeDuoXuan = () => {
		form.setFieldValue([props.name, "multiple"], !multiple);
	};

	const afterOpenChange = (open: boolean) => {
		if (open) {
			const iframe = form.getFieldValue([props.name, "iframe"]);
			setForm.setFieldValue([props.name, "iframe"], iframe);
		}
	};

	const onFinish = (values: { iframe?: string }) => {
		form.setFieldValue([props.name, "iframe"], values.iframe);
		handleCancel();
	};

	useEffect(() => {
		clipboardRef.current = new ClipboardJS(copyBtnRef.current!);

		clipboardRef.current.on("success", () => {
			message.success("复制文本到剪贴板成功！");
		});

		clipboardRef.current.on("error", () => {
			message.error("复制文本到剪贴板失败！");
		});

		return () => {
			clipboardRef.current?.destroy();
		};
	}, []);

	return (
		<>
			<Form.Item name={[props.name, "iframe"]} noStyle />
			<Form.Item name={[props.name, "multiple"]} noStyle />
			<Form.Item name={[props.name, "selector"]} label={props.label} noStyle={props.label ? false : true}>
				<Input
					suffix={
						<div>
							<Button size="small" ref={copyBtnRef} title="复制" color="default" data-clipboard-text={selector} type="text" icon={<CopyOutlined />} />
							<Button
								size="small"
								color={multiple ? "primary" : "default"}
								onClick={handleChangeDuoXuan}
								type="text"
								title="多选或单选"
								styles={{ icon: { color: multiple ? "#1677ff" : undefined } }}
								icon={<OrderedListOutlined />}
							/>
							<Button size="small" icon={<Html5Outlined />} type="text" onClick={handleOpen} />
						</div>
					}
					placeholder="请输入选择器"
					style={{ width: "100%" }}
				/>
			</Form.Item>

			<Modal footer={false} destroyOnClose open={open} onCancel={handleCancel} afterOpenChange={afterOpenChange}>
				<Form layout="vertical" onFinish={onFinish} form={setForm}>
					<Form.Item name="iframe" label="内嵌框架 (iframe)">
						<Input placeholder="https://www.example.com/..." />
					</Form.Item>
					<Flex justify="end" gap={10}>
						<Button onClick={handleCancel}>取消</Button>
						<Button type="primary" htmlType="submit">
							确定
						</Button>
					</Flex>
				</Form>
			</Modal>
		</>
	);
}
